package com.chen.qmzy.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.util.StrUtil;
import com.chen.qmzy.controller.form.LoginForm;
import com.chen.qmzy.controller.form.UserRegisterForm;
import com.chen.qmzy.controller.form.UserUpdateForm;
import com.chen.qmzy.controller.form.UserUpdatePwdForm;
import com.chen.qmzy.controller.vo.UserLoginVO;
import com.chen.qmzy.controller.vo.UserRegisterVO;
import com.chen.qmzy.controller.vo.UserVO;
import com.chen.qmzy.entity.DwReceiverEntity;
import com.chen.qmzy.entity.DwUserEntity;
import com.chen.qmzy.entity.ResultEntity;
import com.chen.qmzy.exception.BusinessException;
import com.chen.qmzy.exception.BusinessExceptionEnum;
import com.chen.qmzy.service.DwUserService;
import com.chen.qmzy.tool.KoDoTool;
import com.chen.qmzy.tool.MD5Util;
import com.chen.qmzy.tool.Result;


import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@CrossOrigin//跨域
@RestController//遵循RestFul
@RequestMapping("v2/DwUser/")
public class DwUserController {
    private static final Logger logger= LoggerFactory.getLogger(DwUserController.class);//日志getLogger需要传入的类名
    @Resource
    private RedisTemplate<String ,String> redisTemplate;//Redis工具类
    @Resource
    DwUserService dwUserService;


    @Resource
    KoDoTool koDoTool;

    @Value("${project.localfilepath}")
    private String localFilePath;//本地文件存储地址

    /**
     * 根据id查询用户信息
     */
    @GetMapping("getDwUserList")
    public Result<UserVO> getDwUserList(){
        Integer userId = StpUtil.getLoginIdAsInt();
        DwUserEntity user = dwUserService.getDwUserList(userId);
        if (user == null) {
            throw new BusinessException(BusinessExceptionEnum.DATA_NOT_EXIST);
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return Result.ok(userVO);
    }

    /**
     * 注册添加用户
     * @return
     */
        @PostMapping("register")
        public  String addDwUser(
                @RequestParam(value = "uname",defaultValue = "-1") String uname,
                @RequestParam(value = "password",defaultValue = "-1") String password,
                @RequestParam(value = "gender",defaultValue = "-1") int gender,
                @RequestParam(value = "email",defaultValue = "-1") String email,
                @RequestParam(value = "phone",defaultValue = "-1") String phone,
                @RequestParam(value = "nickName",defaultValue = "-1") String nickName,
                @RequestParam(value = "remark",defaultValue = "-1") String remark
        ){
            if (uname.equals("")||password.equals("")||email.equals("")){
                return ResultEntity.fail(-10002);
            }
            return dwUserService.addDwUser(uname, password, phone, email, gender, nickName, remark);
        }




    /**
     * 修改用户信息
     */

    @SaCheckLogin
    @PostMapping("updata")
    public Result update(
            @RequestBody @Valid UserUpdateForm form
    ){
        int userId = StpUtil.getLoginIdAsInt();
        //如果不是登录用户数据，则抛出异常
        if (userId != form.getId()) {
            throw new BusinessException(BusinessExceptionEnum.REQUEST_FORBIDEN_DATA_NOT_YOUR);
        }
        DwUserEntity upadate = dwUserService.getDwUserList(userId);
        if (upadate == null) {
            throw new BusinessException(BusinessExceptionEnum.DATA_NOT_EXIST);
        }
        //这里时不能更改密码的
        form.setPassword(null);
        DwUserEntity userForUpdate = new DwUserEntity();
        BeanUtils.copyProperties(form, userForUpdate);

        if (dwUserService.update(
                userForUpdate.getUname(),  userForUpdate.getEmail(),userForUpdate.getPhone(),
               userForUpdate.getGender(), userForUpdate.getNickname(),
                userForUpdate.getId()
        )) {//返回成功
            return Result.ok();
        } else { //返回失败
            return Result.error();
        }
    }
/**
 * 修改用户密码
 */
@SaCheckLogin
@PostMapping("updatapwd")
public Result upadatapwd(@RequestBody @Valid UserUpdatePwdForm form
){
    int userId = StpUtil.getLoginIdAsInt();
    DwUserEntity user = dwUserService.getDwUserList(userId);
    if (user == null) {
        throw new BusinessException(BusinessExceptionEnum.DATA_NOT_EXIST);
    }

    //若密码不为空字符，则表明用户打算更改密码
    String passwordOld = form.getPasswordOld();
//    String passwordOldMd5 = MD5Util.md5Encode(passwordOld + user.getSalt(), "UTF-8");
//    if (!StrUtil.equals(passwordOld, passwordOldMd5)) {
//        throw new BusinessException(BusinessExceptionEnum.USER_OLD_PASSWORD_ERROR);
//    }
//
    String password = user.getPassword();
    if (!StrUtil.equals(passwordOld, password)) {
        throw new BusinessException(BusinessExceptionEnum.USER_OLD_PASSWORD_ERROR);
    }

    String passwordNew = form.getPasswordNew();
    //String passwordMd5 = MD5Util.md5Encode(passwordNew + user.getSalt(), "UTF-8");

//    DwUserEntity userForUpdate = new DwUserEntity();
//    userForUpdate.setId(userId);
//    userForUpdate.setPassword(passwordMd5);

    if (dwUserService.updatapwd(userId,passwordNew)){
        return Result.ok();
    } else {
        return Result.error();
    }
}


    /**
     * 用户登录
     */

    @PostMapping("login")
        public Result<UserLoginVO> login(@RequestBody LoginForm form) {
        DwUserEntity user = dwUserService.login(form.getUname(), form.getPassword());
        int userId = user.getId();
        //客户端注册用户登录
        StpUtil.login(userId);
        String token = StpUtil.getTokenValue();
        UserLoginVO userLoginVO = new UserLoginVO();
        BeanUtils.copyProperties(user, userLoginVO);
        userLoginVO.setToken(token);
      return Result.ok(userLoginVO);
    }

    /**
     * 用户登出
     * @return
     */
    @SaCheckLogin
    @PostMapping("logout")
    public Result logout() {
        StpUtil.logout();
        return Result.ok(); //登出成功
    }
    // 查询 Token 信息  ---- http://localhost:8081/acc/tokenInfo
    @RequestMapping("tokenInfo")
    public SaResult tokenInfo() {
        return SaResult.data(StpUtil.getTokenInfo());
    }

    /**
     * 重置头像
     * @param id
     * @param file
     * @return
     */

    @PostMapping("upFile")
    public String upFile(
            @RequestParam("id") int id,
            @RequestParam("file") MultipartFile file
    ) {
        String SuffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));//获取文件后缀名
        String FileNewName = UUID.randomUUID() + SuffixName;//新的文件名
        File dest = new File(localFilePath + FileNewName);//生成新的文件
        if (!dest.getParentFile().exists()) {//判定文件夹是否存在
            dest.getParentFile().mkdir();//生成文件夹
        }
        try {
            file.transferTo(dest);//将临时文件转为正式文件
            String koDoString = koDoTool.UploadFile(localFilePath + FileNewName);//上传到七牛云
            dwUserService.addAvatar(id,koDoString);
            return ResultEntity.success(koDoString);//返回七牛云的文件路径字符串
        } catch (Exception e) {
            logger.error(e.getMessage());//输出日志
            return ResultEntity.fail(-10001);//返回错误代码
        }
    }

}
